package com.lxp.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lxp.service.OssService;
import com.lxp.utils.OssUtils;
import com.sun.codemodel.internal.JVar;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    //上传头像到Oss 并获取头像的url
    public String uploadAvatar(MultipartFile file) {
        //通过工具类获取各个参数
        String endpoint = OssUtils.END_POIND;
        String accessKeyId = OssUtils.ACCESS_KEY_ID;
        String accessKeySecret = OssUtils.ACCESS_KEY_SECRET;
        String bucketName =OssUtils.BUCKET_NAME;
        //创建Oss类
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try{
            String fileName = file.getOriginalFilename();//获取文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-","");//获取uuid
            fileName=uuid+"_"+fileName;

            //获取日期年月日 来创建文件夹
            String dataTime = new DateTime().toString("yyyy/MM/dd");
            //拼接filename
            fileName="avatar/"+dataTime+"/"+fileName;
            InputStream inputStream = file.getInputStream(); //获取文件输入流
            ossClient.putObject(bucketName,fileName,inputStream); //上传文件
            //https://lxp-edu-project.oss-cn-beijing.aliyuncs.com/avatar/1.jpg url的格式
            //拼接url
            String url ="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }catch (Exception e){

        }finally {
            if (ossClient!=null){
                ossClient.shutdown();// 关闭OSSClient。
            }
        }

        return null;
    }
}
